<template>
  <view class="address-list-container">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="back-btn" @click="goBack">
        <uni-icons type="left" size="24" color="#333"></uni-icons>
      </view>
      <text class="title">收货地址</text>
    </view>
    
    <!-- 地址列表 -->
    <scroll-view scroll-y class="address-scroll" v-if="addressList.length > 0">
      <view class="address-item" 
        v-for="(address, index) in addressList" 
        :key="address._id"
        :class="{'default': address.isDefault}"
        @click="selectAddress(address)"
      >
        <view class="address-info">
          <view class="address-name-phone">
            <text class="name">{{address.name}}</text>
            <text class="phone">{{address.phone}}</text>
            <text class="default-tag" v-if="address.isDefault">默认</text>
          </view>
          <view class="address-detail">
            <text>{{address.city}} {{address.department}} {{address.houseNumber}}</text>
          </view>
        </view>
        <view class="address-actions">
          <view class="action-btn edit" @click.stop="editAddress(address)">
            <uni-icons type="compose" size="20" color="#0086ff"></uni-icons>
            <text>编辑</text>
          </view>
          <view class="action-btn delete" @click.stop="deleteAddress(address._id, index)">
            <uni-icons type="trash" size="20" color="#ff4d4f"></uni-icons>
            <text>删除</text>
          </view>
        </view>
      </view>
    </scroll-view>
    
    <!-- 空地址提示 -->
    <view class="empty-address" v-else>
      <image src="/static/imgs/empty-address.png" mode="aspectFit"></image>
      <text>暂无收货地址</text>
    </view>
    
    <!-- 底部添加按钮 -->
    <view class="add-address-btn" @click="addAddress">
      <text>新增收货地址</text>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      addressList: [],
      fromPage: '', // 来源页面
      loading: false
    }
  },
  onLoad(options) {
    this.fromPage = options.from || '';
    this.loadAddressList();
    
    // 监听地址更新事件
    uni.$on('addressUpdate', this.loadAddressList);
  },
  onUnload() {
    uni.$off('addressUpdate', this.loadAddressList);
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    
    async loadAddressList() {
      this.loading = true;
      try {
        // 优先从本地存储获取
        const localData = uni.getStorageSync('addressList');
        if (localData) {
          this.addressList = JSON.parse(localData);
        } else {
          // 从服务器获取
          const res = await this.requestAddressList();
          if (res.statusCode === 200) {
            this.addressList = res.data;
            uni.setStorageSync('addressList', JSON.stringify(res.data));
          }
        }
      } catch (err) {
        console.error('获取地址失败:', err);
        uni.showToast({
          title: '获取地址失败',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },
    
    requestAddressList() {
      return new Promise((resolve, reject) => {
        uni.request({
          url: 'http://localhost:3000/address',
          success: resolve,
          fail: reject
        });
      });
    },
    
    selectAddress(address) {
      if (this.fromPage === 'order') {
        // 如果是从订单页面跳转过来，选择后返回
        const eventChannel = this.getOpenerEventChannel();
        eventChannel.emit('addressSelected', address);
        uni.navigateBack();
      }
    },
    
    addAddress() {
      uni.navigateTo({
        url: '/pages/me/address-edit'
      });
    },
    
    editAddress(address) {
      uni.navigateTo({
        url: `/pages/me/address-edit?id=${address._id}`
      });
    },
    
    async deleteAddress(id, index) {
      uni.showModal({
        title: '提示',
        content: '确定要删除该地址吗？',
        success: async (res) => {
          if (res.confirm) {
            uni.showLoading({ title: '删除中...', mask: true });
            try {
              // 获取当前列表
              const localData = uni.getStorageSync('addressList');
              let addressList = localData ? JSON.parse(localData) : [];
              
              // 过滤掉要删除的地址
              addressList = addressList.filter(item => item._id !== id);
              
              // 更新存储
              uni.setStorageSync('addressList', JSON.stringify(addressList));
              
              // 更新页面数据
              this.addressList.splice(index, 1);
              
              uni.hideLoading();
              uni.showToast({
                title: '删除成功',
                icon: 'success'
              });
            } catch (err) {
              console.error('删除失败:', err);
              uni.hideLoading();
              uni.showToast({
                title: '删除失败',
                icon: 'none'
              });
            }
          }
        }
      });
    }
  }
}
</script>

<style lang="scss">
.address-list-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
}

.header {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background-color: #fff;
  position: sticky;
  top: 0;
  z-index: 10;
  
  .back-btn {
    margin-right: 20rpx;
  }
  
  .title {
    flex: 1;
    text-align: center;
    font-size: 32rpx;
    font-weight: bold;
  }
}

.address-scroll {
  height: calc(100vh - 180rpx);
  padding: 20rpx;
}

.address-item {
  display: flex;
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  
  &.default {
    border-left: 8rpx solid #0086ff;
  }
  
  .address-info {
    flex: 1;
    
    .address-name-phone {
      display: flex;
      align-items: center;
      margin-bottom: 15rpx;
      
      .name {
        font-size: 30rpx;
        font-weight: bold;
        margin-right: 20rpx;
      }
      
      .phone {
        font-size: 28rpx;
        color: #666;
        margin-right: 20rpx;
      }
      
      .default-tag {
        background-color: #0086ff;
        color: #fff;
        font-size: 22rpx;
        padding: 4rpx 12rpx;
        border-radius: 20rpx;
      }
    }
    
    .address-detail {
      font-size: 28rpx;
      color: #666;
      line-height: 1.6;
    }
  }
  
  .address-actions {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    margin-left: 30rpx;
    
    .action-btn {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 10rpx 15rpx;
      
      text {
        font-size: 24rpx;
        margin-top: 5rpx;
      }
      
      &.edit text {
        color: #0086ff;
      }
      
      &.delete text {
        color: #ff4d4f;
      }
    }
  }
}

.empty-address {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 60vh;
  
  image {
    width: 300rpx;
    height: 300rpx;
    opacity: 0.6;
    margin-bottom: 30rpx;
  }
  
  text {
    font-size: 28rpx;
    color: #999;
  }
}

.add-address-btn {
  position: fixed;
  bottom: 30rpx;
  left: 30rpx;
  right: 30rpx;
  background-color: #0086ff;
  color: #fff;
  text-align: center;
  padding: 25rpx 0;
  border-radius: 50rpx;
  font-size: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 134, 255, 0.3);
  
  &:active {
    opacity: 0.9;
  }
}
</style>